import datetime

from extensions import db


class JobPlan(db.Model):
    """ 业务定时计划 """
    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    app_name = db.Column(db.String(64), comment="业务名称")
    task_id = db.Column(db.String(64),unique=True,nullable=False,comment="任务ID")
    name = db.Column(db.String(64), comment="任务名称")
    method = db.Column(db.String(64), default="GET", comment="API请求方法：GET,POST")
    url = db.Column(db.String(128), comment="URL")
    params = db.Column(db.JSON,default={}, comment="API请求参数")
    trigger_type = db.Column(db.String(64), comment="trigger类型:date,interval,cron")
    trigger_kwargs = db.Column(db.JSON, comment="trigger参数")
    next_run_time = db.Column(db.String(64),comment="下次运行时间")
    status = db.Column(db.Integer, default=1,comment="任务状态:1-运行中 2-已暂停 3-已完成")
    ext = db.Column(db.JSON, comment="业务扩展备注")
    create_time = db.Column(db.DateTime, default=datetime.datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, comment='更新时间')

    @property
    def status_desc(self):
        _mapping = {
            '1': '运行中',
            '2': '已暂停',
            '3': '已完成'
        }
        return _mapping.get(str(self.status), '{}:未定义'.format(self.status))

    def __repr__(self):
        return '<BussinessJob %r>' % self.name



class JobEvent(db.Model):
    """ job 运行事件记录"""
    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    task_id = db.Column(db.String(64),nullable=False,comment="关联任务ID")
    method = db.Column(db.String(64),comment="API请求方法：GET,POST")
    url = db.Column(db.String(128), comment="URL")
    params = db.Column(db.JSON, comment="API请求参数")
    result = db.Column(db.TEXT, comment="响应结果")
    create_time = db.Column(db.DateTime, default=datetime.datetime.now, comment='创建时间')
    update_time = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now, comment='更新时间')
